package model

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

func WithMysql(hand func(db *gorm.DB) error) error {
	dsn := "root:123456@tcp(127.0.0.1:3306)/week2?charset=utf8mb4&parseTime=True&loc=Local"
	DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	defer func() {
		fmt.Println("关闭连接")
		dd, _ := DB.DB()
		err := dd.Close()
		if err != nil {
			log.Printf("msyql close %v", err)

			return
		}
	}()
	return hand(DB)
}

func MysqlConnect() {
	dsn := "root:123456@tcp(127.0.0.1:3306)/week2?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	db.AutoMigrate(&Order{})
}
